package com.zenithmind.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zenithmind.chat.mapper.ChatGroupMemberMapper;
import com.zenithmind.chat.mapper.ChatMessageMapper;
import com.zenithmind.chat.mapper.ChatMessageReadMapper;
import com.zenithmind.chat.pojo.entity.ChatGroupMember;
import com.zenithmind.chat.pojo.entity.ChatMessage;
import com.zenithmind.chat.pojo.entity.ChatMessageRead;
import com.zenithmind.chat.pojo.vo.ChatMessageReadVO;
import com.zenithmind.chat.pojo.vo.ChatUserVO;
import com.zenithmind.chat.service.ChatMessageReadService;
import com.zenithmind.common.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 消息已读服务实现类 - 专业实现
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ChatMessageReadServiceImpl extends ServiceImpl<ChatMessageReadMapper, ChatMessageRead>
        implements ChatMessageReadService {
    
    private final ChatMessageMapper chatMessageMapper;
    private final ChatGroupMemberMapper chatGroupMemberMapper;
    
    @Override
    public List<ChatUserVO> getMessageReadUsers(String messageId) {
        log.info("获取消息已读用户列表，消息ID: {}", messageId);
        
        if (!StringUtils.hasText(messageId)) {
            throw new BusinessException("消息ID不能为空");
        }
        
        // 查询已读记录
        LambdaQueryWrapper<ChatMessageRead> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatMessageRead::getMessageId, messageId)
                   .orderByDesc(ChatMessageRead::getReadTime);
        
        List<ChatMessageRead> readRecords = list(queryWrapper);
        
        // 转换为用户VO列表 (实际项目中应该从用户服务获取用户信息)
        List<ChatUserVO> userList = new ArrayList<>();
        for (ChatMessageRead record : readRecords) {
            ChatUserVO user = new ChatUserVO();
            user.setId(record.getUserId());
            user.setReadTime(record.getReadTime());
            userList.add(user);
        }
        
        return userList;
    }
    
    @Override
    public List<ChatUserVO> getMessageUnreadUsers(String messageId, String groupId) {
        log.info("获取消息未读用户列表，消息ID: {}, 群组ID: {}", messageId, groupId);
        
        if (!StringUtils.hasText(messageId) || !StringUtils.hasText(groupId)) {
            throw new BusinessException("消息ID和群组ID不能为空");
        }
        
        // 查询群组所有成员
        LambdaQueryWrapper<ChatGroupMember> memberQuery = new LambdaQueryWrapper<>();
        memberQuery.eq(ChatGroupMember::getGroupId, groupId)
                  .eq(ChatGroupMember::getIsDeleted, 0);
        List<ChatGroupMember> allMembers = chatGroupMemberMapper.selectList(memberQuery);
        
        // 查询已读记录
        LambdaQueryWrapper<ChatMessageRead> readQuery = new LambdaQueryWrapper<>();
        readQuery.eq(ChatMessageRead::getMessageId, messageId);
        List<ChatMessageRead> readRecords = list(readQuery);
        
        // 获取已读用户ID列表
        List<String> readUserIds = readRecords.stream()
                                             .map(ChatMessageRead::getUserId)
                                             .collect(Collectors.toList());
        
        // 筛选出未读用户
        List<ChatUserVO> unreadUsers = new ArrayList<>();
        for (ChatGroupMember member : allMembers) {
            if (!readUserIds.contains(member.getUserId())) {
                ChatUserVO user = new ChatUserVO();
                user.setId(member.getUserId());
                unreadUsers.add(user);
            }
        }
        
        return unreadUsers;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean markMessageAsRead(String messageId, String userId) {
        log.info("标记消息为已读，消息ID: {}, 用户ID: {}", messageId, userId);
        
        if (!StringUtils.hasText(messageId) || !StringUtils.hasText(userId)) {
            throw new BusinessException("消息ID和用户ID不能为空");
        }
        
        // 检查消息是否存在
        ChatMessage message = chatMessageMapper.selectById(messageId);
        if (message == null) {
            throw new BusinessException("消息不存在");
        }
        
        // 检查是否已标记为已读
        LambdaQueryWrapper<ChatMessageRead> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatMessageRead::getMessageId, messageId)
                   .eq(ChatMessageRead::getUserId, userId);
        
        ChatMessageRead existingRecord = getOne(queryWrapper);
        if (existingRecord != null) {
            // 已经标记过，更新阅读时间
            existingRecord.setReadTime(LocalDateTime.now());
            return updateById(existingRecord);
        } else {
            // 新建已读记录
            ChatMessageRead readRecord = new ChatMessageRead();
            readRecord.setMessageId(messageId);
            readRecord.setUserId(userId);
            readRecord.setReadTime(LocalDateTime.now());
            return save(readRecord);
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchMarkAsRead(List<String> messageIds, String userId) {
        log.info("批量标记消息为已读，消息数量: {}, 用户ID: {}", messageIds.size(), userId);
        
        if (CollectionUtils.isEmpty(messageIds) || !StringUtils.hasText(userId)) {
            throw new BusinessException("消息ID列表和用户ID不能为空");
        }
        
        LocalDateTime now = LocalDateTime.now();
        List<ChatMessageRead> readRecords = new ArrayList<>();
        
        // 查询已存在的已读记录
        LambdaQueryWrapper<ChatMessageRead> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatMessageRead::getUserId, userId)
                   .in(ChatMessageRead::getMessageId, messageIds);
        List<ChatMessageRead> existingRecords = list(queryWrapper);
        
        // 获取已读消息ID
        List<String> readMessageIds = existingRecords.stream()
                                                   .map(ChatMessageRead::getMessageId)
                                                   .collect(Collectors.toList());
        
        // 更新已存在的记录
        for (ChatMessageRead record : existingRecords) {
            record.setReadTime(now);
        }
        
        // 创建新的已读记录
        for (String messageId : messageIds) {
            if (!readMessageIds.contains(messageId)) {
                ChatMessageRead readRecord = new ChatMessageRead();
                readRecord.setMessageId(messageId);
                readRecord.setUserId(userId);
                readRecord.setReadTime(now);
                readRecords.add(readRecord);
            }
        }
        
        // 批量保存和更新
        boolean updateResult = true;
        if (!existingRecords.isEmpty()) {
            updateResult = updateBatchById(existingRecords);
        }
        
        boolean saveResult = true;
        if (!readRecords.isEmpty()) {
            saveResult = saveBatch(readRecords);
        }
        
        return updateResult && saveResult;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean markGroupMessagesAsRead(String groupId, String userId) {
        log.info("标记群组所有消息为已读，群组ID: {}, 用户ID: {}", groupId, userId);
        
        if (!StringUtils.hasText(groupId) || !StringUtils.hasText(userId)) {
            throw new BusinessException("群组ID和用户ID不能为空");
        }
        
        // 查询群组中的所有消息
        LambdaQueryWrapper<ChatMessage> messageQuery = new LambdaQueryWrapper<>();
        messageQuery.eq(ChatMessage::getGroupId, groupId)
                   .eq(ChatMessage::getIsDeleted, 0);
        List<ChatMessage> messages = chatMessageMapper.selectList(messageQuery);
        
        if (CollectionUtils.isEmpty(messages)) {
            return true; // 没有消息需要标记
        }
        
        // 查询已读记录
        List<String> messageIds = messages.stream()
                                         .map(ChatMessage::getId)
                                         .collect(Collectors.toList());
        
        LambdaQueryWrapper<ChatMessageRead> readQuery = new LambdaQueryWrapper<>();
        readQuery.eq(ChatMessageRead::getUserId, userId)
                .in(ChatMessageRead::getMessageId, messageIds);
        List<ChatMessageRead> existingRecords = list(readQuery);
        
        // 获取已读消息ID
        List<String> readMessageIds = existingRecords.stream()
                                                   .map(ChatMessageRead::getMessageId)
                                                   .collect(Collectors.toList());
        
        // 筛选出未读消息
        List<ChatMessageRead> newReadRecords = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        
        for (String messageId : messageIds) {
            if (!readMessageIds.contains(messageId)) {
                ChatMessageRead readRecord = new ChatMessageRead();
                readRecord.setMessageId(messageId);
                readRecord.setUserId(userId);
                readRecord.setReadTime(now);
                newReadRecords.add(readRecord);
            }
        }
        
        if (!CollectionUtils.isEmpty(newReadRecords)) {
            return saveBatch(newReadRecords);
        }
        
        return true;
    }
    
    @Override
    public Boolean checkUserReadMessage(String messageId, String userId) {
        log.info("检查用户是否已读消息，消息ID: {}, 用户ID: {}", messageId, userId);
        
        if (!StringUtils.hasText(messageId) || !StringUtils.hasText(userId)) {
            throw new BusinessException("消息ID和用户ID不能为空");
        }
        
        LambdaQueryWrapper<ChatMessageRead> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatMessageRead::getMessageId, messageId)
                   .eq(ChatMessageRead::getUserId, userId);
        
        return count(queryWrapper) > 0;
    }
    
    @Override
    public LocalDateTime getUserLastReadTime(String groupId, String userId) {
        log.info("查询用户在群组中的最后已读时间，群组ID: {}, 用户ID: {}", groupId, userId);
        
        if (!StringUtils.hasText(groupId) || !StringUtils.hasText(userId)) {
            throw new BusinessException("群组ID和用户ID不能为空");
        }
        
        // 查询群组中的所有消息
        LambdaQueryWrapper<ChatMessage> messageQuery = new LambdaQueryWrapper<>();
        messageQuery.eq(ChatMessage::getGroupId, groupId)
                   .eq(ChatMessage::getIsDeleted, 0);
        List<ChatMessage> messages = chatMessageMapper.selectList(messageQuery);
        
        if (CollectionUtils.isEmpty(messages)) {
            return null; // 没有消息
        }
        
        // 获取消息ID列表
        List<String> messageIds = messages.stream()
                                         .map(ChatMessage::getId)
                                         .collect(Collectors.toList());
        
        // 查询用户的已读记录
        LambdaQueryWrapper<ChatMessageRead> readQuery = new LambdaQueryWrapper<>();
        readQuery.eq(ChatMessageRead::getUserId, userId)
                .in(ChatMessageRead::getMessageId, messageIds)
                .orderByDesc(ChatMessageRead::getReadTime);
        
        Page<ChatMessageRead> page = new Page<>(1, 1);
        Page<ChatMessageRead> result = page(page, readQuery);
        
        if (result.getRecords().isEmpty()) {
            return null;
        }
        
        return result.getRecords().get(0).getReadTime();
    }
    
    @Override
    public Integer countMessageReadUsers(String messageId) {
        log.info("统计消息已读数量，消息ID: {}", messageId);
        
        if (!StringUtils.hasText(messageId)) {
            throw new BusinessException("消息ID不能为空");
        }
        
        LambdaQueryWrapper<ChatMessageRead> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatMessageRead::getMessageId, messageId);
        
        return Math.toIntExact(count(queryWrapper));
    }
    
    @Override
    public Integer countUserUnreadMessages(String groupId, String userId) {
        log.info("统计用户未读消息数量，群组ID: {}, 用户ID: {}", groupId, userId);
        
        if (!StringUtils.hasText(groupId) || !StringUtils.hasText(userId)) {
            throw new BusinessException("群组ID和用户ID不能为空");
        }
        
        // 查询群组中的所有消息
        LambdaQueryWrapper<ChatMessage> messageQuery = new LambdaQueryWrapper<>();
        messageQuery.eq(ChatMessage::getGroupId, groupId)
                   .eq(ChatMessage::getIsDeleted, 0);
        List<ChatMessage> messages = chatMessageMapper.selectList(messageQuery);
        
        if (CollectionUtils.isEmpty(messages)) {
            return 0; // 没有消息
        }
        
        // 获取消息ID列表
        List<String> messageIds = messages.stream()
                                         .map(ChatMessage::getId)
                                         .collect(Collectors.toList());
        
        // 查询用户的已读记录
        LambdaQueryWrapper<ChatMessageRead> readQuery = new LambdaQueryWrapper<>();
        readQuery.eq(ChatMessageRead::getUserId, userId)
                .in(ChatMessageRead::getMessageId, messageIds);
        List<ChatMessageRead> readRecords = list(readQuery);
        
        // 获取已读消息ID
        List<String> readMessageIds = readRecords.stream()
                                               .map(ChatMessageRead::getMessageId)
                                               .collect(Collectors.toList());
        
        // 计算未读消息数量
        return (int) messageIds.stream()
                             .filter(id -> !readMessageIds.contains(id))
                             .count();
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer cleanExpiredReadRecords(Integer days) {
        log.info("清理过期已读记录，保留天数: {}", days);
        
        if (days == null || days < 0) {
            throw new BusinessException("保留天数不能为空或负数");
        }
        
        // 计算截止日期
        LocalDateTime cutoffDate = LocalDateTime.now().minusDays(days);
        
        LambdaQueryWrapper<ChatMessageRead> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.lt(ChatMessageRead::getReadTime, cutoffDate);
        
        int count = Math.toIntExact(count(queryWrapper));
        if (count > 0) {
            remove(queryWrapper);
        }
        
        return count;
    }
    
    @Override
    public Object getReadStatistics(String messageId, String groupId, String startTime, String endTime) {
        log.info("获取已读统计信息，消息ID: {}, 群组ID: {}, 开始时间: {}, 结束时间: {}", 
                messageId, groupId, startTime, endTime);
        
        // 构建查询条件
        LambdaQueryWrapper<ChatMessageRead> queryWrapper = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(messageId)) {
            queryWrapper.eq(ChatMessageRead::getMessageId, messageId);
        }
        
        if (StringUtils.hasText(groupId)) {
            // 查询群组中的所有消息
            LambdaQueryWrapper<ChatMessage> messageQuery = new LambdaQueryWrapper<>();
            messageQuery.eq(ChatMessage::getGroupId, groupId)
                       .eq(ChatMessage::getIsDeleted, 0);
            List<ChatMessage> messages = chatMessageMapper.selectList(messageQuery);
            
            if (!CollectionUtils.isEmpty(messages)) {
                List<String> messageIds = messages.stream()
                                                .map(ChatMessage::getId)
                                                .collect(Collectors.toList());
                queryWrapper.in(ChatMessageRead::getMessageId, messageIds);
            } else {
                // 没有消息，返回空统计
                return new HashMap<>();
            }
        }
        
        // 处理时间范围
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        
        if (StringUtils.hasText(startTime)) {
            try {
                LocalDateTime startDateTime = LocalDateTime.parse(startTime, formatter);
                queryWrapper.ge(ChatMessageRead::getReadTime, startDateTime);
            } catch (Exception e) {
                log.warn("解析开始时间失败: {}", startTime);
            }
        }
        
        if (StringUtils.hasText(endTime)) {
            try {
                LocalDateTime endDateTime = LocalDateTime.parse(endTime, formatter);
                queryWrapper.le(ChatMessageRead::getReadTime, endDateTime);
            } catch (Exception e) {
                log.warn("解析结束时间失败: {}", endTime);
            }
        }
        
        // 查询已读记录
        List<ChatMessageRead> readRecords = list(queryWrapper);
        
        // 按消息ID分组
        Map<String, List<ChatMessageRead>> messageReadMap = readRecords.stream()
                                                                     .collect(Collectors.groupingBy(ChatMessageRead::getMessageId));
        
        // 按用户ID分组
        Map<String, List<ChatMessageRead>> userReadMap = readRecords.stream()
                                                                  .collect(Collectors.groupingBy(ChatMessageRead::getUserId));
        
        // 按日期分组
        Map<LocalDate, List<ChatMessageRead>> dateReadMap = readRecords.stream()
                                                                     .collect(Collectors.groupingBy(record -> 
                                                                         record.getReadTime().toLocalDate()));
        
        // 构建统计结果
        Map<String, Object> result = new HashMap<>();
        result.put("totalReadCount", readRecords.size());
        result.put("messageReadCounts", messageReadMap.entrySet().stream()
                                       .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().size())));
        result.put("userReadCounts", userReadMap.entrySet().stream()
                                   .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().size())));
        result.put("dateReadCounts", dateReadMap.entrySet().stream()
                                   .collect(Collectors.toMap(date -> date.toString(), e -> e.getValue().size())));
        
        return result;
    }
    
    // Controller调用的方法实现
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean markAsRead(String messageId, String userId) {
        return markMessageAsRead(messageId, userId);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean markAllAsRead(String userId, String groupId, String sessionId) {
        log.info("标记全部为已读，用户ID: {}, 群组ID: {}, 会话ID: {}", userId, groupId, sessionId);
        
        if (!StringUtils.hasText(userId)) {
            throw new BusinessException("用户ID不能为空");
        }
        
        if (StringUtils.hasText(groupId)) {
            return markGroupMessagesAsRead(groupId, userId);
        } else if (StringUtils.hasText(sessionId)) {
            // 标记会话消息为已读
            // 查询会话中的所有消息
            LambdaQueryWrapper<ChatMessage> messageQuery = new LambdaQueryWrapper<>();
            messageQuery.eq(ChatMessage::getGroupId, sessionId)
                       .eq(ChatMessage::getIsDeleted, 0);
            List<ChatMessage> messages = chatMessageMapper.selectList(messageQuery);
            
            if (CollectionUtils.isEmpty(messages)) {
                return true; // 没有消息需要标记
            }
            
            List<String> messageIds = messages.stream()
                                            .map(ChatMessage::getId)
                                            .collect(Collectors.toList());
            
            return batchMarkAsRead(messageIds, userId);
        } else {
            throw new BusinessException("群组ID和会话ID不能同时为空");
        }
    }
    
    @Override
    public List<ChatMessageReadVO> getMessageReaders(String messageId) {
        log.info("获取消息阅读者列表，消息ID: {}", messageId);
        
        List<ChatUserVO> users = getMessageReadUsers(messageId);
        List<ChatMessageReadVO> result = new ArrayList<>();
        
        for (ChatUserVO user : users) {
            ChatMessageReadVO vo = new ChatMessageReadVO();
            vo.setUserId(user.getId());
            vo.setReadTime(user.getReadTime());
            // 设置阅读状态为已读
            vo.setReadStatus(1);
            // 实际项目中应该从用户服务获取用户详细信息
            result.add(vo);
        }
        
        return result;
    }
    
    @Override
    public List<String> getUnreadUsers(String messageId) {
        log.info("获取未读用户列表，消息ID: {}", messageId);
        
        if (!StringUtils.hasText(messageId)) {
            throw new BusinessException("消息ID不能为空");
        }
        
        // 获取消息所在的群组
        ChatMessage message = chatMessageMapper.selectById(messageId);
        if (message == null) {
            throw new BusinessException("消息不存在");
        }
        
        List<ChatUserVO> unreadUsers = getMessageUnreadUsers(messageId, message.getGroupId());
        
        return unreadUsers.stream()
                        .map(ChatUserVO::getId)
                        .collect(Collectors.toList());
    }
    
    @Override
    public Integer getUserUnreadCount(String userId, String groupId, String sessionId) {
        log.info("获取用户未读数量，用户ID: {}, 群组ID: {}, 会话ID: {}", userId, groupId, sessionId);
        
        if (!StringUtils.hasText(userId)) {
            throw new BusinessException("用户ID不能为空");
        }
        
        if (StringUtils.hasText(groupId)) {
            return countUserUnreadMessages(groupId, userId);
        } else if (StringUtils.hasText(sessionId)) {
            // 统计会话未读消息
            return countUserUnreadMessages(sessionId, userId);
        } else {
            throw new BusinessException("群组ID和会话ID不能同时为空");
        }
    }
    
    @Override
    public Integer getGroupUnreadCount(String groupId, String userId) {
        log.info("获取群组未读数量，群组ID: {}, 用户ID: {}", groupId, userId);
        
        if (!StringUtils.hasText(groupId) || !StringUtils.hasText(userId)) {
            throw new BusinessException("群组ID和用户ID不能为空");
        }
        
        return countUserUnreadMessages(groupId, userId);
    }
    
    @Override
    public Integer getSessionUnreadCount(String sessionId, String userId) {
        log.info("获取会话未读数量，会话ID: {}, 用户ID: {}", sessionId, userId);
        
        if (!StringUtils.hasText(sessionId) || !StringUtils.hasText(userId)) {
            throw new BusinessException("会话ID和用户ID不能为空");
        }
        
        return countUserUnreadMessages(sessionId, userId);
    }
    
    @Override
    public Boolean isMessageRead(String messageId, String userId) {
        log.info("检查消息是否已读，消息ID: {}, 用户ID: {}", messageId, userId);
        
        return checkUserReadMessage(messageId, userId);
    }
    
    @Override
    public ChatMessageReadVO getMessageReadStatistics(String messageId) {
        log.info("获取消息已读统计，消息ID: {}", messageId);
        
        if (!StringUtils.hasText(messageId)) {
            throw new BusinessException("消息ID不能为空");
        }
        
        // 查询消息
        ChatMessage message = chatMessageMapper.selectById(messageId);
        if (message == null) {
            throw new BusinessException("消息不存在");
        }
        
        // 查询已读记录
        LambdaQueryWrapper<ChatMessageRead> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatMessageRead::getMessageId, messageId);
        List<ChatMessageRead> readRecords = list(queryWrapper);
        
        // 统计已读人数
        int readCount = readRecords.size();
        
        // 查询群组总人数
        LambdaQueryWrapper<ChatGroupMember> memberQuery = new LambdaQueryWrapper<>();
        memberQuery.eq(ChatGroupMember::getGroupId, message.getGroupId())
                  .eq(ChatGroupMember::getIsDeleted, 0);
        Long totalMembers = chatGroupMemberMapper.selectCount(memberQuery);
        
        // 计算未读人数
        int unreadCount = totalMembers.intValue() - readCount;
        
        // 构建统计结果
        ChatMessageReadVO vo = new ChatMessageReadVO();
        vo.setMessageId(messageId);
        // 设置消息内容
        vo.setMessageContent(message.getContent());
        // 设置群组ID
        vo.setGroupId(message.getGroupId());
        // 设置已读状态
        vo.setReadStatus(readCount > 0 ? 1 : 0);
        
        return vo;
    }
    
    @Override
    public Object getGroupReadStatistics(String groupId, String startDate, String endDate) {
        log.info("获取群组已读统计，群组ID: {}, 开始日期: {}, 结束日期: {}", groupId, startDate, endDate);
        
        return getReadStatistics(null, groupId, startDate, endDate);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateReadTime(String messageId, String userId) {
        log.info("更新已读时间，消息ID: {}, 用户ID: {}", messageId, userId);
        
        if (!StringUtils.hasText(messageId) || !StringUtils.hasText(userId)) {
            throw new BusinessException("消息ID和用户ID不能为空");
        }
        
        // 查询已读记录
        LambdaQueryWrapper<ChatMessageRead> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatMessageRead::getMessageId, messageId)
                   .eq(ChatMessageRead::getUserId, userId);
        
        ChatMessageRead readRecord = getOne(queryWrapper);
        if (readRecord == null) {
            // 不存在记录，创建新记录
            return markMessageAsRead(messageId, userId);
        } else {
            // 更新已读时间
            readRecord.setReadTime(LocalDateTime.now());
            return updateById(readRecord);
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer clearReadRecords(Integer days) {
        log.info("清理已读记录，保留天数: {}", days);
        
        return cleanExpiredReadRecords(days);
    }
    
    @Override
    public List<ChatMessageReadVO> getUserReadHistory(String userId, Integer page, Integer size) {
        log.info("获取用户已读历史，用户ID: {}, 页码: {}, 页大小: {}", userId, page, size);
        
        if (!StringUtils.hasText(userId)) {
            throw new BusinessException("用户ID不能为空");
        }
        
        // 查询用户的已读记录
        LambdaQueryWrapper<ChatMessageRead> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatMessageRead::getUserId, userId)
                   .orderByDesc(ChatMessageRead::getReadTime);
        
        Page<ChatMessageRead> pageParam = new Page<>(page, size);
        Page<ChatMessageRead> result = page(pageParam, queryWrapper);
        
        // 转换为VO
        List<ChatMessageReadVO> voList = new ArrayList<>();
        for (ChatMessageRead record : result.getRecords()) {
            ChatMessageReadVO vo = new ChatMessageReadVO();
            vo.setMessageId(record.getMessageId());
            vo.setUserId(record.getUserId());
            vo.setReadTime(record.getReadTime());
            
            // 获取消息内容（实际项目中应该批量查询以提高性能）
            ChatMessage message = chatMessageMapper.selectById(record.getMessageId());
            if (message != null) {
                vo.setMessageContent(message.getContent());
                vo.setGroupId(message.getGroupId());
                vo.setSenderId(message.getSenderId());
                // 设置创建时间作为发送时间
                vo.setCreateTime(message.getCreateTime());
            }
            
            voList.add(vo);
        }
        
        return voList;
    }
} 